package com.ghxxzx.dagl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ghxxzx.dagl.entity.*;
import com.ghxxzx.dagl.exceptions.JyException;
import com.ghxxzx.dagl.mapper.ClxxMapper;
import com.ghxxzx.dagl.mapper.DajyMapper;
import com.ghxxzx.dagl.mapper.DalxMapper;
import com.ghxxzx.dagl.service.JyService;
import com.ghxxzx.dagl.utils.*;
import com.ghxxzx.dagl.vo.*;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import io.swagger.annotations.*;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipOutputStream;

@Api(value = "借阅")
@RestController
@RequestMapping("/jy/api")
public class JyController {
    @Autowired
    private JyService jyService;
    @Autowired
    private DajyMapper dajyMapper;
    @Autowired
    private PathUtils pathUtils;
    @Autowired
    private ClxxMapper clxxMapper;
    @Autowired
    private DalxMapper dalxMapper;
    @Autowired
    private WsFlag wsFlag;
    Logger log = LoggerFactory.getLogger(getClass());

    @ApiOperation(value = "获取pdf", notes = "查询")
    @RequestMapping("/getPdf//{clxxName}//{dah}/{fileName}/{jyId}")
    public void getPdf(@PathVariable String dah, @PathVariable String clxxName, @PathVariable String fileName, @PathVariable Integer jyId
            , @ApiParam(hidden = true) HttpServletRequest request,
                       @ApiParam(hidden = true) HttpServletResponse response, HttpSession httpSession
    ) {

        FileInputStream inputStream = null;
        ServletOutputStream out = null;
        FileOutputStream outputStream = null;
        User user1 = (User) httpSession.getAttribute("user");
        User user = new User();
        user.setPhone(user1.getPhone());
        user.setName(user1.getName());
        String stringDate = "";
        if (jyId == 0) {
            user = new User();
            user.setName("入馆中");
            user.setPhone(",");
            stringDate = "北京时间:" + getStringDate(new Date());
        } else {
            Dajy dajy = dajyMapper.selectById(jyId);
            user.setPhone(":" + user.getPhone());
            stringDate = ",借阅时间:" + getStringDate(dajy.getShsj());
        }

        File tempFile = null;
        String path = pathUtils.getPath();
        path = path + "/" + clxxName + "/" + dah + "/" + fileName;
        try {
//            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//            tempFile = File.createTempFile(Buling.Buyema(user.getName()), "." + suffix);
//            outputStream = new FileOutputStream(tempFile);
//            addWatermark(outputStream, path, user.getName()+ user.getPhone() + stringDate, null);
            File file = new File(path);
            inputStream = new FileInputStream(file);
            out = response.getOutputStream();
            IOUtils.copy(inputStream,out);
        } catch (JyException e) {
            log.error(e.getMess(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "下载", notes = "查询")
    @RequestMapping(value = "download")
    public void download(String[] ids, Integer jyId
            , @ApiParam(hidden = true) HttpServletRequest request,
                         @ApiParam(hidden = true) HttpServletResponse response, HttpSession httpSession
    ) {
        Dajy dajy = dajyMapper.selectById(jyId);
//        String code = wsFlag.getCode(dajy.getDabh());
//        Integer byCode = dalxMapper.findByCode(code);
        Integer byCode = wsFlag.getTypeId(dajy.getDabh());
        Dalx dalx = dalxMapper.selectById(byCode);

        response.reset();
        response.setContentType("APPLICATION/OCTET-STREAM");

        String utilsPath = pathUtils.getPath();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String temp = "D:\\zaiptemFile\\" + uuid + "\\" + dajy.getDabh();
        File file = new File(temp);
        if (!file.exists()) {
            file.mkdirs();
        }
        byte[] b = new byte[4096];
        int len = 1024;
        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        File ftp = null;
        try {
//            if (lx != 2) {
            for (int w = 0; w < ids.length; w++) {
                String path = ids[w];

                path = URLDecoder.decode(path, "utf-8");
                int i = path.lastIndexOf(".");
                if (i == -1) {
                    continue;
                }
                String suffix = path.substring(i + 1);
                if (suffix.equalsIgnoreCase("pdf")) {
                    ids[w] = (utilsPath + "\\" + path);
                }
            }
//            }
            for (String path : ids) {
                path = URLDecoder.decode(path, "utf-8");
                File file1 = new File(path);
                if (file1.isDirectory()) {
                    continue;
                } else {
                    int i = path.lastIndexOf(".");
                    if (i == -1) {
                        continue;
                    }
                }
                String[] strings = path.split(dajy.getDabh());
                if (strings.length==1){
                    continue;
                }
                path=(utilsPath+"/"+dalx.getDalxName()+"/"+dajy.getDabh()+strings[1]);

                String[] split = path.split(dajy.getDabh());
                String s = split[1];
                int i = s.lastIndexOf("\\");
                String substring = "";
                if (i == -1) {
                    substring = path;
                } else {
                    substring = s.substring(0, i);
                }

                String temptarget = (temp + substring);
                new File(temptarget).mkdirs();
                FileUtils.copyFile2(path, (temp + s));
//                copyImg(dajy, path, temp);
            }

            out = response.getOutputStream();
            String zip = CompressUtil.zipFile(file, "zip");
            ftp = ResourceUtils.getFile(zip);
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(ftp.getName(), "UTF-8"));//设置头部信息
            inputStream = new FileInputStream(ftp);
            while ((len = inputStream.read(b)) != -1) {
                out.write(b, 0, len);
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            DeleteFileUtils.deleteDirectory("D:\\zaiptemFile\\" + uuid);
            if (ftp != null) {
                ftp.delete();
            }
        }
    }

    private void copyPdf(Dajy dajy, String path, String temp) {
        File file1 = new File("C:\\zaiptemFile");
        if (!file1.exists()) {
            file1.mkdirs();
        }
        file1 = new File("C:\\zaiptemFile\\" + dajy.getDabh());
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File file = new File(path);
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        File tempFile = null;
        try {
            File tempFile1 = new File("C:\\temp");
            if (!tempFile1.exists()) {
                tempFile1.mkdirs();
            }
            if (file.exists()) {
                String suffix = path.substring(path.lastIndexOf(".") + 1);
                String prefix = file.getName().substring(0, file.getName().lastIndexOf("."));
                String name = prefix + "." + suffix;
                tempFile = new File("C:\\temp\\" + name);
                outputStream = new FileOutputStream(tempFile);
//                addWatermark(outputStream, path,user.getName() + user.getPhone()+ stringDate, null);
                inputStream = new FileInputStream(tempFile);
                outputStream = new FileOutputStream("C:\\zaiptemFile\\" + dajy.getDabh() + "\\" + file.getName());
                FileCopyUtils.copy(inputStream, outputStream);
            }
        } catch (JyException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }

    private void copyImg(Dajy dajy, String path, String temp) {
        File file1 = new File("C:\\zaiptemFile");
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String[] strings = path.split(dajy.getDabh());
        String string = strings[1];
        int i = string.lastIndexOf("\\");
        String substring = string.substring(0, i);
        String s = "C:\\zaiptemFile\\" + dajy.getDabh() + substring;
        String[] ss = s.split("\\\\");
        String tempPath = "";
        if (ss.length >= 4) {
            for (int i1 = 0; i1 < ss.length; i1++) {
                if (i1 == 0) {
                    tempPath += ss[i1];
                } else {
                    tempPath += ("\\" + ss[i1]);
                    file1 = new File(tempPath);
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
                }
            }
        } else {
            throw new JyException("文件路劲错误");
        }
        File file = new File(path);
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        File tempFile = null;
        try {
            if (file.exists()) {
                inputStream = new FileInputStream(file);
                outputStream = new FileOutputStream("C:\\zaiptemFile\\" + dajy.getDabh() + string);
                FileCopyUtils.copy(inputStream, outputStream);
            }
        } catch (JyException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "切换图片获取id", notes = "查找")
    @RequestMapping(value = "upanddownImg")
    public ResultEntity upanddownImg(@RequestBody UpanddownImgVo upanddownImgVo) {
        try {
            return jyService.upanddownImg(upanddownImgVo.getLxNodes(), upanddownImgVo.getId(), upanddownImgVo.getType());
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "获取图片", notes = "查询")
    @ApiImplicitParam(name = "path", value = "路劲", required = true, paramType = "query", dataType = "string")
    @RequestMapping(value = "getImg")
    public void getImg(String path, Integer jyId
            , @ApiParam(hidden = true) HttpServletRequest request,
                       @ApiParam(hidden = true) HttpServletResponse response, HttpSession httpSession
    ) {
        FileInputStream inputStream = null;
        ServletOutputStream out = null;
        FileOutputStream outputStream = null;
        User user1 = (User) httpSession.getAttribute("user");
        User user = new User();
        user.setPhone(user1.getPhone());
        user.setName(user1.getName());
        String stringDate = "";
        if (jyId == 0) {
            user = new User();
            user.setName("入馆中");
            user.setPhone(",");
            stringDate = "北京时间:" + getStringDate(new Date());
        } else {
            user.setPhone(":" + user.getPhone());
            Dajy dajy = dajyMapper.selectById(jyId);
            stringDate = ",借阅时间:" + getStringDate(dajy.getShsj());
        }
        File tempFile = null;
        try {
            path = URLDecoder.decode(path, "utf-8");
            File file = new File(path);
            if (file.exists()) {
//                String suffix = path.substring(path.lastIndexOf(".") + 1);
//                tempFile = File.createTempFile(Buling.Buyema(user.getName()), "." + suffix);
                inputStream = new FileInputStream(file);
//                inputStream = addWatermark(path, user.getName() + user.getPhone() + stringDate, suffix, tempFile);
                out = response.getOutputStream();
                IOUtils.copy(inputStream,out);
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getStringDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String s = format.format(date);
        return s;
    }

    //一次复制一个字节，异常处理，手动关闭流
    public void copyFile(String srcFilename, String destFilename) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(srcFilename);
            fileOutputStream = new FileOutputStream(destFilename);
            int cc = fileInputStream.read();
            //如果cc不是-1，把cc保存到目标文件中
            while (cc != -1) {
                fileOutputStream.write(cc);
                cc = fileInputStream.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param bos           输出文件的位置
     * @param input         原PDF位置
     * @param waterMarkName 页脚添加水印
     * @param permission    权限码
     * @throws DocumentException
     * @throws IOException
     */
    public void addWatermark(OutputStream bos, String input, String waterMarkName, Integer permission) throws Exception {
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, bos);

        // 获取总页数 +1, 下面从1开始遍历
        int total = reader.getNumberOfPages() + 1;
        // 使用classpath下面的字体库
//        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        BaseFont base = null;
        try {
            //使用winds系统的字体
            base = BaseFont.createFont("c:\\windows\\fonts\\FZSTK.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 间隔
        int interval = -200;
        // 获取水印文字的高度和宽度
        int textH = 0, textW = 0;
        JLabel label = new JLabel();
        label.setText(waterMarkName);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());
        System.out.println("textH: " + textH);
        System.out.println("textW: " + textW);

        // 设置水印透明度
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.1f);
        gs.setStrokeOpacity(0.1f);

        com.itextpdf.text.Rectangle pageSizeWithRotation = null;
        PdfContentByte content = null;
        for (int i = 1; i < total; i++) {
            // 在内容上方加水印
            content = stamper.getOverContent(i);
            // 在内容下方加水印
            // content = stamper.getUnderContent(i);
            content.saveState();
            content.setGState(gs);

            // 设置字体和字体大小
            content.beginText();
            content.setFontAndSize(base, 20);

            // 获取每一页的高度、宽度
            pageSizeWithRotation = reader.getPageSizeWithRotation(i);
            float pageHeight = pageSizeWithRotation.getHeight();
            float pageWidth = pageSizeWithRotation.getWidth();

            // 根据纸张大小多次添加， 水印文字成30度角倾斜
            for (int height = interval + textH; height < pageHeight; height = height + textH * 3) {
                for (int width = interval + textW; width < pageWidth + textW; width = width + textW * 2) {
                    content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
                }
            }

            content.endText();
        }

        // 关流
        stamper.close();
        reader.close();
    }

    /**
     * @Description newImage
     * @Explain 新建图片（指定图片尺寸）
     **/
    public FileInputStream addWatermark(String sourceImgPath, String waterMarkContent, String fileExt, File tempFile) {
        //水印字体，大小 颜色 文字的旋转角度 透明度
//        Font font = new Font("宋体", Font.BOLD, Font.BOLD,buffImg.getWidth(null)/300*20));//水印
        Color markContentColor = Color.gray;
        Integer degree = 45;
        float alpha = 0.3f;
//        Font font=null;
        OutputStream outImgStream = null;
        FileInputStream inputStream = null;
        try {
            File srcImgFile = new File(sourceImgPath);//得到文件
            Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
//            Font font = new Font("宋体", Font.BOLD, Font.BOLD,bufImg.getWidth(null)/300*20);
            double i = bufImg.getWidth(null) / 300.0;
            if (i <= 0.5) {
                i = 1;
            }
            Double size = bufImg.getWidth(null) / 300.0 * 10;
            int intValue = size.intValue();

            Font font = new Font("宋体", Font.BOLD, intValue);
            Graphics2D g = bufImg.createGraphics();//得到画笔
//            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(
                    srcImg.getScaledInstance(srcImg.getWidth(null),
                            srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
                    null);
            g.setColor(markContentColor); //设置水印颜色
            g.setFont(font);              //设置字体
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));//设置水印文字透明度
            if (null != degree) {
//                g.rotate(Math.toRadians(degree));//设置水印旋转
                g.rotate(Math.toRadians(degree),
                        (double) bufImg.getWidth() / 2,
                        (double) bufImg.getHeight() / 2);
            }
//            JLabel label = new JLabel(waterMarkContent);
            g.drawString(waterMarkContent, (bufImg.getWidth() - (bufImg.getWidth(null) / 300) * 15 * 650 / 56) / 2, bufImg.getHeight() / 2);
       /*     FontMetrics metrics = label.getFontMetrics(font);
            int width = metrics.stringWidth(label.getText());//文字水印的宽
            int rowsNumber = srcImgHeight / width;// 图片的高  除以  文字水印的宽    ——> 打印的行数(以文字水印的宽为间隔)
            int columnsNumber = srcImgWidth / width;//图片的宽 除以 文字水印的宽   ——> 每行打印的列数(以文字水印的宽为间隔)
            //防止图片太小而文字水印太长，所以至少打印一次
            if (rowsNumber < 1) {
                rowsNumber = 1;
            }
            if (columnsNumber < 1) {
                columnsNumber = 1;
            }
            for (int j = 0; j < rowsNumber; j++) {
                for (int i = 0; i < columnsNumber; i++) {
                    g.drawString(waterMarkContent, i * width + j * width, -i * width + j * width);//画出水印,并设置水印位置
                }
            }*/
            g.dispose();// 释放资源
            // 输出图片
            outImgStream = new FileOutputStream(tempFile);
            ImageIO.write(bufImg, fileExt, outImgStream);
            inputStream = new FileInputStream(tempFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        } finally {
            try {
                if (outImgStream != null) {
                    outImgStream.flush();
                    outImgStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                e.getMessage();
            }
        }
        return inputStream;
    }

    @ApiOperation(value = "查询借阅材料信息", notes = "添加")
    @ApiImplicitParam(name = "id", value = "借阅id", required = true, paramType = "query", dataType = "id")
    @RequestMapping(value = "queryJyClxx")
    public ResultEntity queryJyClxx(Integer id) {
        try {
            Dajy dajy = dajyMapper.findById(id);
            Date dqsj = dajy.getDqsj();
            if (dqsj == null) {
                return ResultEntity.error("该档案借阅未通过,请耐心等待通过");
            }
            Date date = new Date();
            Boolean sfgq = sfgq(dqsj, date);
            if (sfgq) {
                return jyService.queryJyClxx(id);
            } else {
                throw new JyException("该借阅已过期");
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    public Boolean sfgq(Date dqsj, Date newDate) {
        long dqsjTime = dqsj.getTime();
        long time = newDate.getTime();
        if (dqsjTime >= time) {
            return true;
        } else {
            return false;
        }
    }

    @ApiOperation(value = "檔案借阅", notes = "添加")
    @RequestMapping(value = "batchdaJy")
    public ResultEntity batchdaJy(String[] dabhs, String jyyy, Integer shrId, Integer jysc, Integer dalxId, HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            if (user == null) {
                user = new User();
            }
            Integer id = user.getId();
            return jyService.batchdaJy(dabhs, jyyy, shrId, jysc, id, dalxId);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "檔案借阅", notes = "添加")
    @RequestMapping(value = "daJy")
    public ResultEntity daJy(@RequestBody Dajy dajy, HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            if (user == null) {
                user = new User();
            }
            Integer id = user.getId();
            return jyService.daJy(dajy, dajy.getShrId(), id, dajy.getClxxIds());
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "借阅审批查询Id", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询条件", required = true, paramType = "query", dataType = "id"),
    })
    @RequestMapping(value = "queryJyspId")
    public ResultEntity queryJyspId(String id) {
        try {
//            User user = (User) httpSession.getAttribute("user");
//            if (user==null){
//                user=new User();
//            }
//            user.setId(4);
//            Integer userId = user.getId();
            return jyService.queryJyspId(id);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "借阅审批查询", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "查询条件", required = false, paramType = "query", dataType = "keyword"),
            @ApiImplicitParam(name = "zt", value = "查询类型", required = false, paramType = "query", dataType = "zt"),
            @ApiImplicitParam(name = "pageSize", value = "查询每页显示条数", required = true, paramType = "query", dataType = "pageSize"),
            @ApiImplicitParam(name = "pageNumber", value = "查询当前页", required = true, paramType = "query", dataType = "pageNumber")
    })
    @RequestMapping(value = "queryJysp")
    public ResultEntity queryJysp(String keyword, Integer zt, String sort, Integer pageSize, Integer pageNum, HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            Integer id = user.getId();
            return jyService.queryJysp(keyword, zt, sort, pageSize, pageNum, id);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "我的借阅", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "查询条件", required = false, paramType = "query", dataType = "keyword"),
            @ApiImplicitParam(name = "zt", value = "查询类型", required = false, paramType = "query", dataType = "zt"),
            @ApiImplicitParam(name = "pagesize", value = "查询每页显示条数", required = true, paramType = "query", dataType = "pagesize"),
            @ApiImplicitParam(name = "pagenumber", value = "查询当前页", required = true, paramType = "query", dataType = "pagenumber")
    })
    @RequestMapping(value = "queryJy")
    public ResultEntity queryJy(String keyword, Integer zt, String sort, Integer pageSize, Integer pageNum, HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            Integer id = user.getId();
            return jyService.queryJy(keyword, zt, sort, pageSize, pageNum, id);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "借阅审批", notes = "更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "审批结果", required = true, paramType = "query", dataType = "type"),
            @ApiImplicitParam(name = "id", value = "借阅id", required = true, paramType = "query", dataType = "id")
    })
    @RequestMapping(value = "Jysp")
    public ResultEntity Jysp(Integer type, Integer id) {
        try {
            Dajy dajy = dajyMapper.selectById(id);
            if (type == 1) {
                Date date = new Date();
                Date addDate = addDate(date, dajy.getJysx());
                dajy.setShsj(date);
                dajy.setDqsj(addDate);
                dajy.setZt(type + "");
            } else {
                dajy.setShsj(new Date());
                dajy.setZt(type + "");
            }
            dajyMapper.updateById(dajy);
            return ResultEntity.ok();
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "借阅批量审批", notes = "更新")
    @RequestMapping(value = "JyBatchsp")
    public ResultEntity JyBatchsp(Integer type, Integer[] ids) {
        try {
            for (Integer id : ids) {
                Dajy dajy = dajyMapper.selectById(id);
                if (type == 1) {
                    Date date = new Date();
                    Date addDate = addDate(date, dajy.getJysx());
                    dajy.setShsj(date);
                    dajy.setDqsj(addDate);
                    dajy.setZt(type + "");
                } else {
                    dajy.setShsj(new Date());
                    dajy.setZt(type + "");
                }
                dajyMapper.updateById(dajy);
            }
            return ResultEntity.ok();
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }


    public static Date addDate(Date date, long day) throws ParseException {
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
        time += day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }

    @ApiOperation(value = "根据档案号查询材料", notes = "查询")
    @RequestMapping(value = "queryDabhClxx")
    public ResultEntity queryDabhClxx(String dabh) {
        try {
            dabh = dabh.trim();
            return jyService.queryDabhClxx(dabh);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

}
